package com.superman.util;

import java.io.IOException;
import java.sql.*;
import java.util.Properties;

public class ConnectionFactory {
    private static String driver;
    private static String url;
    private static String username;
    private static String password;

    static {
        Properties properties = new Properties();
        try {
            properties.load(ConnectionFactory.class.getResourceAsStream("jdbcinfo.properties"));
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() throws ClassNotFoundException, SQLException {
        Connection conn = null;
        Class.forName(driver);
        conn = DriverManager.getConnection(url, username, password);
        return conn;
    }

    public static void close(ResultSet rs, Statement stmt, Connection conn) throws SQLException {
        if(rs != null){
            rs.close();
        }
        if(stmt != null){
            stmt.close();
        }

        if(conn != null){
            conn.close();
        }
    }

    public static void close(Statement stmt, Connection conn) throws SQLException {
        close(null, stmt, conn);
    }

    public static void close(Statement stmt) throws SQLException {
        close(null, stmt, null);
    }

    public static void close(Connection conn) throws SQLException {
        close(null, null, conn);
    }
}
